from sqlalchemy.orm import Session
from typing import List, Optional
from app.models.asphalt_test import AsphaltTest, AsphaltSample, AsphaltCurveData
from app.schemas.asphalt_test import AsphaltTestCreate
from datetime import datetime

def create_asphalt_test(db: Session, data: dict) -> AsphaltTest:
    """
    创建沥青试验数据
    """
    # 创建试验数据
    db_test = AsphaltTest(
        equipment_number=data["equNum"],
        precative_number=data["precativeNum"],
        trial_date=datetime.strptime(data["trialDate"], "%Y-%m-%d %H:%M:%S")
    )
    db.add(db_test)
    db.flush()  # 获取 test_id

    # 创建样本数据
    for sample_data in data["dataList"]:
        db_sample = AsphaltSample(
            test_id=db_test.id,
            sample_id=sample_data["sampleId"],
            compression_strength=sample_data["kyqd"],
            compression_load=sample_data["kyhz"]
        )
        db.add(db_sample)
        db.flush()  # 获取 sample_id

        # 创建曲线数据
        for idx, curve_point in enumerate(sample_data["cruve"]):
            x_value, y_value = map(float, curve_point.split(","))
            db_curve = AsphaltCurveData(
                sample_id=db_sample.id,
                x_value=x_value,
                y_value=y_value,
                data_order=idx
            )
            db.add(db_curve)

    db.commit()
    db.refresh(db_test)
    return db_test

def get_asphalt_test(db: Session, test_id: str) -> Optional[AsphaltTest]:
    """
    获取指定ID的沥青试验数据
    """
    return db.query(AsphaltTest).filter(AsphaltTest.id == test_id).first()

def list_asphalt_tests(
    db: Session,
    skip: int = 0,
    limit: int = 10
) -> List[AsphaltTest]:
    """
    获取沥青试验数据列表
    """
    return db.query(AsphaltTest).offset(skip).limit(limit).all()

def update_asphalt_test(
    db: Session,
    test_id: str,
    data: dict
) -> Optional[AsphaltTest]:
    """
    更新沥青试验数据
    """
    db_test = get_asphalt_test(db, test_id)
    if not db_test:
        return None
    
    # 更新基本信息
    for key, value in data.items():
        if hasattr(db_test, key):
            setattr(db_test, key, value)
    
    db.commit()
    db.refresh(db_test)
    return db_test

def delete_asphalt_test(db: Session, test_id: str) -> bool:
    """
    删除沥青试验数据
    """
    db_test = get_asphalt_test(db, test_id)
    if not db_test:
        return False
    
    db.delete(db_test)
    db.commit()
    return True 